import { createSlice, Draft, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";

// 定义新闻类型
interface News {}
interface ChannelNewsItem {
  distance: number;
}
// 状态切片管理的状态的类型
interface ChannelNews {
  // 频道id -> 新闻列表
  [cid: string]: ChannelNewsItem;
}

// 合并后的 ChannelNewsItem 定义
interface ChannelNewsItem {
  results: News[];
  pre_timestamp: string | null;
  distance: number;
}

const initialState: ChannelNews = {};

// 创建用于管理新闻列表数据的状态切片
const { reducer: newsReducer, actions } = createSlice({
  name: "news",
  initialState,
  reducers: {
    // 保存新闻列表
    saveNews(state, action) {
      const { cid, results, pre_timestamp } = action.payload;
      if (typeof state[cid] === 'undefined') {
        state[cid] = {
          results,
          pre_timestamp,
          distance: 0 // 初始化滚动距离
        }
      } else {
        // 修正拼写错误，将 reslts 改为 results
        state[cid].results.push(...results); 
        state[cid].pre_timestamp = pre_timestamp
      }
    },
    // 保存内容区域滚动距离(区分不同频道的新闻内容区域)
    saveDistance(
      state: Draft<ChannelNews>,
      action: PayloadAction<{ cid: string; distance: number }>
    ) {
      if (state[action.payload.cid]) {
        state[action.payload.cid].distance = action.payload.distance;
      }
    },
    
  },
});

// 新闻列表状态选择器
export const selectChannelNews =
  (cid: string) =>
  (state: AppState): undefined | ChannelNewsItem => {
    return state.newsReducer[cid];
  };

export const { saveNews, saveDistance } = actions;
export default newsReducer;